package com.chujiu.utils;


import com.chujiu.utils.sign.SignVerifyHandle;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;


/**
  * 无视Https证书是否正确的Java Http Client
  *
  *
  * @author wz
  *
  * @create 2012.8.17
  * @version 1.0
  */
@Component
public class HttpsUtil {
 private static final Logger logger = LoggerFactory.getLogger(HttpsUtil.class);
 @Autowired
 private SignVerifyHandle signVerifyHandle;
 @Value("${chujiu-court.vip_num}")
 private String VIP_NUM;
 @Value("${chujiu-court.version_id}")
 private  String VERSION_ID;

 /**
  * 忽视证书HostName
  */
 private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
     public boolean verify(String s, SSLSession sslsession) {
         logger.warn("WARNING: Hostname is not matched for cert.");
         return true;
     }
 };

  /**
  * Ignore Certification
  */
 private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
     private X509Certificate[] certificates;
     public void checkClientTrusted(X509Certificate certificates[],
             String authType) throws CertificateException {
         if (this.certificates == null) {
             this.certificates = certificates;
             logger.info("init at checkClientTrusted");
         }
     }
     public void checkServerTrusted(X509Certificate[] ax509certificate,
             String s) throws CertificateException {
         if (this.certificates == null) {
             this.certificates = ax509certificate;
             logger.info("init at checkServerTrusted");
         }

     }
     public X509Certificate[] getAcceptedIssuers() {
         // TODO Auto-generated method stub
         return null;
     }
 };


    /**
     * post提交方式
     */
    public static  String doPost(String urlString,String postData){
        String result=null;
        try {
            HttpClient httpClient=new DefaultHttpClient();
            HttpPost requestPost=new HttpPost(urlString);
            requestPost.addHeader("Content-type","application/json; charset=utf-8");
            requestPost.setHeader("Accept", "application/json");

                    /*List<NameValuePair> list=new ArrayList<NameValuePair>();
                    list.add(new BasicNameValuePair("postData", postData));*/

            requestPost.setEntity(new StringEntity(postData,"UTF-8"));
            HttpResponse response = httpClient.execute(requestPost);

            if(response.getStatusLine().getStatusCode()==200){
                HttpEntity entity = response.getEntity();
                result= EntityUtils.toString(entity,"utf-8");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }






    /**
     * 拿到token值
     * @param map
     * @return
     */
    public  String getResultMap(Map<String,String> map){
        String tokeyString=null;
        Map<String, String> headMap = HFJsonUtil.getJsonToMap(map.get("head"));
        if(headMap!=null&&headMap.containsKey("code")){
            if(headMap.get("code").equals("000000")){
                if(signVerifyHandle.verifySign(VIP_NUM, map.get("body"), headMap.get("signData"))){
                    Map<String, String> data= HFJsonUtil.getJsonToMap(map.get("body"));
                    tokeyString=data.get("token");
                }else{
                    logger.info("token验签结果:验签失败");
                }
            }else {
                logger.info("token信息查询返回信息:"+"||"+headMap.get("message"));
            }
        }
        return tokeyString;
    }


    public static void main(String... args) {
        //token发送报文
       // String urlString = "http://192.168.2.169:8080/gzcw-app/sysController/getToken.html";

       //用户信息查询
       //String urlString = "http://192.168.2.152:8020/gzcw-app/customerController/queryCustInfo.html";
        HttpsUtil httpsUtil=new HttpsUtil();
       // httpsUtil.sendToken(new HashMap<>(),urlString);

    }


}